/**
 * @file teacher.js
 * @description 教师管理相关API路由处理
 * @created 2024-07-04
 */

import express from 'express'
const router = express.Router()

// 获取学院列表
// GET /api/admin/colleges/list/
router.get('/admin/colleges/list/', (req, res) => {
  console.log('获取学院列表请求')
  
  // 生成模拟学院数据
  const collegesData = {
    status: 'success',
    data: {
      colleges: generateCollegesList()
    }
  }
  
  res.json(collegesData)
})

// 获取特定学院的系部列表
// GET /api/admin/colleges/:collegeId/departments/
router.get('/admin/colleges/:collegeId/departments/', (req, res) => {
  const { collegeId } = req.params
  console.log(`获取学院(ID: ${collegeId})的系部列表`)
  
  // 生成模拟系部数据
  const departmentsData = {
    status: 'success',
    data: {
      college: getCollegeInfo(collegeId),
      departments: generateDepartmentsList(collegeId)
    }
  }
  
  res.json(departmentsData)
})

// 获取特定系部的教师列表
// GET /api/admin/departments/:departmentId/teachers/
router.get('/admin/departments/:departmentId/teachers/', (req, res) => {
  const { departmentId } = req.params
  console.log(`获取系部(ID: ${departmentId})的教师列表`)
  
  // 生成模拟教师数据
  const teachersData = {
    status: 'success',
    data: {
      department: getDepartmentInfo(departmentId),
      teachers: generateTeachersByDepartment(departmentId)
    }
  }
  
  res.json(teachersData)
})

// 获取教师详情
// GET /api/admin/teachers/:teacherId/detail/
router.get('/admin/teachers/:teacherId/detail/', (req, res) => {
  const { teacherId } = req.params
  console.log(`获取教师(ID: ${teacherId})详情`)
  
  // 生成模拟教师详情数据
  const teacherDetail = {
    status: 'success',
    data: generateTeacherDetail(teacherId)
  }
  
  res.json(teacherDetail)
})

// 获取教师的教学任务
// GET /api/admin/teachers/:teacherId/assignments/
router.get('/admin/teachers/:teacherId/assignments/', (req, res) => {
  const { teacherId } = req.params
  console.log(`获取教师(ID: ${teacherId})的教学任务`)
  
  // 生成模拟教学任务数据
  const teachingAssignments = {
    status: 'success',
    data: {
      teacher: getTeacherBasicInfo(teacherId),
      assignments: generateTeachingAssignments(teacherId)
    }
  }
  
  res.json(teachingAssignments)
})

// 获取教师特定课程的班级列表
// GET /api/admin/teachers/:teacherId/courses/:courseId/classes/
router.get('/admin/teachers/:teacherId/courses/:courseId/classes/', (req, res) => {
  const { teacherId, courseId } = req.params
  console.log(`获取教师(ID: ${teacherId})的课程(ID: ${courseId})班级列表`)
  
  // 生成模拟班级数据
  const classesData = {
    status: 'success',
    data: {
      teacher: getTeacherBasicInfo(teacherId),
      course: getCourseInfo(courseId),
      classes: generateClassesByCourse(teacherId, courseId)
    }
  }
  
  res.json(classesData)
})

// 获取班级学生成绩
// GET /api/admin/teachers/:teacherId/courses/:courseId/classes/:classId/grades/
router.get('/admin/teachers/:teacherId/courses/:courseId/classes/:classId/grades/', (req, res) => {
  const { teacherId, courseId, classId } = req.params
  console.log(`获取教师(ID: ${teacherId})的课程(ID: ${courseId})班级(ID: ${classId})学生成绩`)
  
  // 生成模拟学生成绩数据
  const gradesData = {
    status: 'success',
    data: generateStudentGrades(teacherId, courseId, classId)
  }
  
  res.json(gradesData)
})

// 生成学院列表
function generateCollegesList() {
  return [
    { id: 1, name: '计算机科学与技术学院', description: '培养计算机科学与技术领域的高素质人才', status: 1 },
    { id: 2, name: '经济与金融学院', description: '培养经济金融领域的专业人才', status: 1 },
    { id: 3, name: '电子信息工程学院', description: '培养电子信息工程领域的专业人才', status: 1 },
    { id: 4, name: '医学院', description: '培养医学领域的专业人才', status: 1 },
    { id: 5, name: '法学院', description: '培养法学领域的专业人才', status: 1 },
    { id: 6, name: '外国语学院', description: '培养外语领域的专业人才', status: 1 }
  ]
}

// 获取学院信息
function getCollegeInfo(collegeId) {
  const colleges = generateCollegesList()
  return colleges.find(college => college.id === parseInt(collegeId)) || { id: collegeId, name: `学院${collegeId}` }
}

// 生成系部列表
function generateDepartmentsList(collegeId) {
  const departmentsMap = {
    1: [
      { id: 101, name: '计算机科学系', description: '主要研究计算机科学理论与应用', college_id: 1, status: 1 },
      { id: 102, name: '软件工程系', description: '培养软件开发与项目管理人才', college_id: 1, status: 1 },
      { id: 103, name: '网络工程系', description: '培养网络技术与安全人才', college_id: 1, status: 1 }
    ],
    2: [
      { id: 201, name: '金融学系', description: '主要研究金融理论与实践', college_id: 2, status: 1 },
      { id: 202, name: '国际经济系', description: '培养国际贸易与经济人才', college_id: 2, status: 1 },
      { id: 203, name: '会计系', description: '培养会计与财务管理人才', college_id: 2, status: 1 }
    ],
    3: [
      { id: 301, name: '电子工程系', description: '主要研究电子技术与应用', college_id: 3, status: 1 },
      { id: 302, name: '通信工程系', description: '培养通信技术人才', college_id: 3, status: 1 },
      { id: 303, name: '自动化系', description: '培养自动化控制技术人才', college_id: 3, status: 1 }
    ],
    4: [
      { id: 401, name: '临床医学系', description: '主要培养临床医学人才', college_id: 4, status: 1 },
      { id: 402, name: '基础医学系', description: '培养基础医学研究人才', college_id: 4, status: 1 },
      { id: 403, name: '护理学系', description: '培养专业护理人才', college_id: 4, status: 1 }
    ],
    5: [
      { id: 501, name: '民商法系', description: '主要研究民法商法理论与实践', college_id: 5, status: 1 },
      { id: 502, name: '刑法系', description: '培养刑事法律人才', college_id: 5, status: 1 },
      { id: 503, name: '国际法系', description: '培养国际法律人才', college_id: 5, status: 1 }
    ],
    6: [
      { id: 601, name: '英语系', description: '主要培养英语语言文学人才', college_id: 6, status: 1 },
      { id: 602, name: '日语系', description: '培养日语语言文学人才', college_id: 6, status: 1 },
      { id: 603, name: '翻译系', description: '培养专业翻译人才', college_id: 6, status: 1 }
    ]
  }
  
  return departmentsMap[collegeId] || []
}

// 获取系部信息
function getDepartmentInfo(departmentId) {
  // 从系部ID推算出学院ID
  const collegeId = Math.floor(parseInt(departmentId) / 100)
  const departments = generateDepartmentsList(collegeId)
  return departments.find(dept => dept.id === parseInt(departmentId)) || { id: departmentId, name: `系部${departmentId}` }
}

// 生成特定系部的教师列表
function generateTeachersByDepartment(departmentId) {
  const teachers = []
  const deptInfo = getDepartmentInfo(departmentId)
  const collegeId = deptInfo.college_id
  
  // 为系部生成5-10位教师
  const teacherCount = Math.floor(Math.random() * 6) + 5
  
  for (let i = 0; i < teacherCount; i++) {
    const teacherId = parseInt(departmentId) * 10 + i
    
    teachers.push({
      id: teacherId,
      teacher_code: `T${String(teacherId).padStart(6, '0')}`,
      name: generateTeacherName(),
      gender: Math.random() > 0.5 ? '男' : '女',
      title: generateTitle(),
      department_id: parseInt(departmentId),
      college_id: collegeId,
      email: `teacher${teacherId}@example.com`,
      phone: `1385${String(teacherId).padStart(7, '0')}`,
      status: 1
    })
  }
  
  return teachers
}

// 获取教师基本信息
function getTeacherBasicInfo(teacherId) {
  const departmentId = Math.floor(parseInt(teacherId) / 10)
  const deptInfo = getDepartmentInfo(departmentId)
  
  return {
    id: parseInt(teacherId),
    teacher_code: `T${String(teacherId).padStart(6, '0')}`,
    name: generateTeacherName(),
    gender: Math.random() > 0.5 ? '男' : '女',
    title: generateTitle(),
    department_id: departmentId,
    department_name: deptInfo.name,
    college_id: deptInfo.college_id,
    college_name: getCollegeInfo(deptInfo.college_id).name
  }
}

// 生成教师详情
function generateTeacherDetail(teacherId) {
  const teacherBasic = getTeacherBasicInfo(teacherId)
  
  // 添加额外的详细信息
  return {
    ...teacherBasic,
    education: generateEducation(),
    entry_date: generateEntryDate(),
    address: '北京市海淀区学院路38号',
    bio: '毕业于北京大学，主要研究方向包括...',
    teaching_assignments: generateTeachingAssignments(teacherId).slice(0, 3) // 只显示前3个教学任务
  }
}

// 生成教学任务
function generateTeachingAssignments(teacherId) {
  const assignments = []
  const assignmentCount = Math.floor(Math.random() * 5) + 1
  
  for (let i = 0; i < assignmentCount; i++) {
    const courseId = parseInt(teacherId) * 10 + i
    const classIds = []
    const classCount = Math.floor(Math.random() * 3) + 1
    
    // 生成班级ID列表
    for (let j = 0; j < classCount; j++) {
      classIds.push(courseId * 10 + j)
    }
    
    assignments.push({
      id: parseInt(teacherId) * 100 + i,
      teacher_id: parseInt(teacherId),
      course_id: courseId,
      course_name: getCourseInfo(courseId).name,
      class_count: classCount,
      class_ids: classIds,
      semester: `2024-${Math.floor(Math.random() * 2) + 1}`,
      year: 2024,
      status: 1
    })
  }
  
  return assignments
}

// 获取课程信息
function getCourseInfo(courseId) {
  const departmentId = Math.floor(parseInt(courseId) / 10)
  const collegeId = Math.floor(departmentId / 100)
  
  const courseNames = {
    1: ['Java程序设计', 'Python编程基础', '数据结构', '计算机网络', '操作系统', '数据库原理', '人工智能导论'],
    2: ['微观经济学', '宏观经济学', '金融市场', '会计学原理', '财务管理', '证券投资学', '国际贸易'],
    3: ['电路分析基础', '数字电子技术', '模拟电子技术', '通信原理', '信号与系统', '移动通信', '卫星通信'],
    4: ['人体解剖学', '生理学', '病理学', '药理学', '内科学', '外科学', '妇产科学'],
    5: ['法理学', '宪法学', '民法学', '刑法学', '商法学', '经济法学', '国际法学'],
    6: ['综合英语', '高级英语', '英语写作', '英语口语', '英语翻译理论与实践', '日语精读', '日语会话']
  }
  
  const courseIndex = courseId % 7
  const courseName = courseNames[collegeId]?.[courseIndex] || `课程${courseId}`
  
  return {
    id: parseInt(courseId),
    course_code: `C${String(courseId).padStart(6, '0')}`,
    name: courseName,
    credit: Math.floor(Math.random() * 2) + 2,
    hours: (Math.floor(Math.random() * 2) + 2) * 16,
    department_id: departmentId,
    college_id: collegeId,
    description: `${courseName}是一门重要的专业课程，包括...`,
    status: 1
  }
}

// 生成课程的班级列表
function generateClassesByCourse(teacherId, courseId) {
  const classes = []
  const classCount = Math.floor(Math.random() * 3) + 1
  
  for (let i = 0; i < classCount; i++) {
    const classId = parseInt(courseId) * 10 + i
    const studentCount = Math.floor(Math.random() * 30) + 20
    
    classes.push({
      id: classId,
      class_code: `CL${String(classId).padStart(6, '0')}`,
      name: `${i + 1}班`,
      grade_year: Math.floor(Math.random() * 4) + 2020,
      department_id: Math.floor(parseInt(courseId) / 10),
      college_id: Math.floor(parseInt(courseId) / 1000),
      student_count: studentCount,
      status: 1
    })
  }
  
  return classes
}

// 生成班级学生成绩
function generateStudentGrades(teacherId, courseId, classId) {
  const studentCount = Math.floor(Math.random() * 30) + 20
  const students = []
  const grades = []
  
  // 获取课程评分类别
  const scoreCategories = [
    { id: 1, name: '出勤', weight: 0.1 },
    { id: 2, name: '作业', weight: 0.3 },
    { id: 3, name: '期末考试', weight: 0.6 }
  ]
  
  // 生成学生列表和成绩
  for (let i = 0; i < studentCount; i++) {
    const studentId = parseInt(classId) * 100 + i
    const student = {
      id: studentId,
      student_code: `S${String(studentId).padStart(6, '0')}`,
      name: generateStudentName(),
      gender: Math.random() > 0.5 ? '男' : '女',
      class_id: parseInt(classId)
    }
    
    students.push(student)
    
    // 为每个评分类别生成成绩
    const attendance = Math.floor(Math.random() * 20) + 80
    const homework = Math.floor(Math.random() * 20) + 80
    const exam = Math.floor(Math.random() * 30) + 70
    
    scoreCategories.forEach(category => {
      let score = 0
      if (category.id === 1) score = attendance
      else if (category.id === 2) score = homework
      else if (category.id === 3) score = exam
      
      grades.push({
        grade_id: studentId * 10 + category.id,
        student_id: studentId,
        category_id: category.id,
        score: score
      })
    })
  }
  
  // 计算最终成绩和统计数据
  const finalGrades = students.map(student => {
    const studentGrades = grades.filter(grade => grade.student_id === student.id)
    let finalScore = 0
    
    studentGrades.forEach(grade => {
      const category = scoreCategories.find(cat => cat.id === grade.category_id)
      finalScore += grade.score * category.weight
    })
    
    finalScore = Math.round(finalScore)
    
    return {
      ...student,
      grades: studentGrades,
      final_score: finalScore
    }
  })
  
  // 按最终成绩排序
  finalGrades.sort((a, b) => b.final_score - a.final_score)
  
  // 更新排名
  finalGrades.forEach((student, index) => {
    student.rank = index + 1
  })
  
  // 计算统计数据
  const avgScore = Math.round(finalGrades.reduce((sum, student) => sum + student.final_score, 0) / finalGrades.length)
  const maxScore = Math.max(...finalGrades.map(student => student.final_score))
  const minScore = Math.min(...finalGrades.map(student => student.final_score))
  const passCount = finalGrades.filter(student => student.final_score >= 60).length
  const excellentCount = finalGrades.filter(student => student.final_score >= 90).length
  
  // 生成成绩分布数据
  const scoreDistribution = {
    categories: ['不及格(0-59)', '及格(60-69)', '良好(70-79)', '优良(80-89)', '优秀(90-100)'],
    values: [0, 0, 0, 0, 0]
  }
  
  finalGrades.forEach(student => {
    const score = student.final_score
    if (score < 60) {
      scoreDistribution.values[0]++
    } else if (score < 70) {
      scoreDistribution.values[1]++
    } else if (score < 80) {
      scoreDistribution.values[2]++
    } else if (score < 90) {
      scoreDistribution.values[3]++
    } else {
      scoreDistribution.values[4]++
    }
  })
  
  return {
    teacher: getTeacherBasicInfo(teacherId),
    course: getCourseInfo(courseId),
    class: {
      id: parseInt(classId),
      class_code: `CL${String(classId).padStart(6, '0')}`,
      name: `${classId % 10 + 1}班`
    },
    score_categories: scoreCategories,
    stats: {
      student_count: finalGrades.length,
      avg_score: avgScore,
      max_score: maxScore,
      min_score: minScore,
      pass_rate: (passCount / finalGrades.length) * 100,
      excellent_rate: (excellentCount / finalGrades.length) * 100
    },
    score_distribution: scoreDistribution,
    students: finalGrades
  }
}

// 生成随机教师姓名
function generateTeacherName() {
  const surnames = ['张', '王', '李', '赵', '陈', '刘', '杨', '黄', '周', '吴', '朱', '孙', '马', '胡', '林']
  const names = ['伟', '芳', '娜', '秀英', '敏', '静', '强', '磊', '洋', '艳', '勇', '军', '杰', '娟', '涛']
  
  return surnames[Math.floor(Math.random() * surnames.length)] + names[Math.floor(Math.random() * names.length)]
}

// 生成随机学生姓名
function generateStudentName() {
  const surnames = ['张', '王', '李', '赵', '陈', '刘', '杨', '黄', '周', '吴', '朱', '孙', '马', '胡', '林']
  const names = ['伟', '芳', '娜', '秀英', '敏', '静', '强', '磊', '洋', '艳', '勇', '军', '杰', '娟', '涛']
  
  return surnames[Math.floor(Math.random() * surnames.length)] + names[Math.floor(Math.random() * names.length)]
}

// 生成随机职称
function generateTitle() {
  const titles = ['教授', '副教授', '讲师', '助教']
  const weights = [0.1, 0.2, 0.5, 0.2]
  
  const random = Math.random()
  let sum = 0
  
  for (let i = 0; i < titles.length; i++) {
    sum += weights[i]
    if (random < sum) {
      return titles[i]
    }
  }
  
  return titles[2] // 默认为讲师
}

// 生成随机学历
function generateEducation() {
  const educations = ['博士', '硕士', '学士']
  const weights = [0.3, 0.6, 0.1]
  
  const random = Math.random()
  let sum = 0
  
  for (let i = 0; i < educations.length; i++) {
    sum += weights[i]
    if (random < sum) {
      return educations[i]
    }
  }
  
  return educations[1] // 默认为硕士
}

// 生成随机入职日期
function generateEntryDate() {
  const year = Math.floor(Math.random() * 10) + 2010
  const month = Math.floor(Math.random() * 12) + 1
  const day = Math.floor(Math.random() * 28) + 1
  
  return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
}

export default router 